package com.mywork.mvpkodeingithub.common

import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.mywork.common.utils.getNow
import com.mywork.mvpkodeingithub.base.view.BaseView
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

fun <T> Observable<T>.execute(baseView: BaseView, lifecycleOwner: LifecycleOwner, subscriber: Observer<T>) =
    this.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .doOnSubscribe(object : Consumer<Disposable> {
            override fun accept(t: Disposable?) {
                baseView.showLoading()
            }
        })
        .doFinally {
            baseView.hideLoading()
        }
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe(subscriber)

/*fun <T> Observable<T>.execute(subscriber: BaseSubscriber<T>, lifecycleOwner: LifecycleOwner) =
    this.observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY))
        .subscribe(subscriber)*/

/*fun <T> Observable<BaseResp<T>>.convert(): Observable<T> {
    return this.flatMap(BaseFunc())
}

fun <T> Observable<BaseResp<T>>.convertBoolean(): Observable<Boolean> {
    return this.flatMap(BaseFuncBoolean())
}*/

fun TextView.LogMsg(msg: String) {
    val now = getNow("HH:mm:ss")
    this.append("$now\n$msg\n")
    val offset = this.lineCount * this.lineHeight
    if (offset > this.height - this.lineHeight) {
        this.scrollTo(0, offset - this.height + this.lineHeight)
    }
}

